<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-17
 * Time: 下午4:25
 */
namespace User\Model;
use Think\Model;

class UserModel extends Model{
    protected $tablePrefix = 'k_';
    protected $connection = UC_DB_DSN;

    /* 用户模型自动验证 */
    protected $_validate = array(
        /* 验证用户名 */
        array('username', '1,30', -1, self::EXISTS_VALIDATE, 'length'), //用户名长度不合法
        array('username', '', -3, self::EXISTS_VALIDATE, 'unique'), //用户名被占用

        /* 验证密码 */
        array('password', '6,30', -4, self::EXISTS_VALIDATE, 'length'), //密码长度不合法

        /* 验证手机号码 */
        array('tel','/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/',-9,self::EXISTS_VALIDATE),//手机号码不合法

        /* 验证邮箱 */
        array('email', 'email', -5, self::EXISTS_VALIDATE), //邮箱格式不正确
        array('email', '1,32', -6, self::EXISTS_VALIDATE, 'length'), //邮箱长度不合法
        array('email', 'checkDenyEmail', -7, self::EXISTS_VALIDATE, 'callback'), //邮箱禁止注册
        array('email', '', -8, self::EXISTS_VALIDATE, 'unique'), //邮箱被占用
    );
    //自动生成
    protected $_auto = array(
        array('password', 'md5', self::MODEL_INSERT, 'function')
    );


    /*
     * 用户注册
     */
    public function register($username,$password,$email,$tel){
        $data = array(
            'username'=>$username,
            'password'=>$password,
            'email'=>$email,
            'tel'=>$tel,
            'status'=>1,
        );
        if($this->create($data)){
            $uid = $this->add();
            return $uid ? $uid : 0;
        }else{
            return $this->getError();
        }
    }
    /*
     * 用户注册
     */
    public function register1($depart,$password){
        $model = M('user','k_','mysqli://root:sdasda@192.168.1.212:3306/user');
        $data = array(
            'username'  =>$depart['username'],
            'password'  =>md5($password),
            'email'     =>$depart['email'],
            'city'      =>$depart['city'],
            'name'      =>$depart['name'],
            'typeid'    =>$depart['typeid'],
            'status'    =>1,
        );
        if($model->where("username='$depart[username]'")->find()){
            return -3;
        }
        if($model->where("email='$depart[email]'")->find()){
            return -8;
        }
        if($uid = $model->add($data)){
            return $uid ? $uid : 0;
        }else{
            return $this->getError();
        }
    }
    /*
     * 用户登录
     */
    public function login($username,$password){
        $map['username'] = $username;
        //获取用户数据
        $user = $this->where($map)->find();
        if(is_array($user) && $user['status']){
            if(md5($password) === $user['password']){
                return $user['id'];
            }else{
                return -2;  //密码错误
            }
        }else{
            return -1; //用户不存在或者禁用
        }
    }

    /*
     * 获取用户信息
     */
    public function info($uid, $is_username = false){
        $map = array();
        if($is_username){ //通过用户名获取
            $map['username'] = $uid;
        } else {
            $map['id'] = $uid;
        }
        $user = $this->where($map)->field(true)->find();
        if(is_array($user) && $user['status'] = 1){
            return $user;
        } else {
            return -1; //用户不存在或被禁用
        }
    }

    /*
     * 更新用户信息
     */
    public function updateUserFields($uid, $data){
//        $model = M('user','k_','mysqli://root:sdasda@192.168.1.212:3306/user');
        if(empty($uid) && empty($data)) {
            $this->error = '参数错误';
            return false;
        }
        //查询邮箱是否存在
        if($data['email'] != ''){
            $arr = $this->where("email='$data[email]' and id!='$uid'")->find();
            if($arr['id']){
                return -4;
            }
        }
        return ($this->where("id='$uid'")->save($data));
    }

    /*
     * 添加用户信息
     */
    public function addInfo ($array) {
        //查询邮箱是否存在
        if($array['email'] != ''){
            $arr = $this->where("email='$array[email]'")->find();
            if($arr['id']){
                return -1;
            }
        }
        //查询用户名是否存在
        if($array['username'] != ''){
            $arr = $this->where("username='$array[username]'")->find();
            if($arr['id']){
                return -2;
            }
        }
        $uid = $this->add($array);
        return $uid ? $uid : -3;
    }
    /*
     *检测用户名是否注册
     */

    public function checkUsername($userName){
        $map['username'] = $userName;
        return $this->where($map)->find();
    }
    /*
    * 得到该机构的用户信息
    */
    public function selectInfo ($where=array(),$field=true){
        $options    =   array();
        $REQUEST    =   (array)I('get.');

        $total      =   $this->where($where)->count();
        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if($total>$listRows){
            $page->setConfig('prev','上一页');
            $page->setConfig('next','下一页');
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %HEADER%');
        }
        $p =$page->show();
//            $this->assign('_page', $p? $p: '');
//            $this->assign('_total',$total);
        $options['limit']   = $page->firstRow.','.$page->listRows;
        $result['showpage'] = $p;
        $this->setProperty('options',$options);
        $result['m'] = $this->where($where)->field($field)->order('id desc')->select();
        return $result;

    }
    public function selectInfo1($where=array(),$field=true){
        return $this->where($where)->field($field)->order('id asc')->select();
    }
    /**
     * 检测邮箱是不是被禁止注册
     * @param  string $email 邮箱
     * @return boolean       ture - 未禁用，false - 禁止注册
     */
    protected function checkDenyEmail($email){
        return true; //TODO: 暂不限制，下一个版本完善
    }
}